<template>
    <div class="form-container">
        <div class="group-setting-tip-info">
            1、分组功能仅针对签字模式和拍照模式有效。<br />
            2、开启分组后，可以对每个签名进行分类。大屏端部分展示效果可以根据分类显示不同的效果。<br />
            3、签名合成效果可以根据当前所在的分类合成相应的效果。<br />
        </div>
        <h4 class="form-title">分组设置</h4>
        <el-form :model="groupFormData" label-width="120px" ref="groupFormRef">
            <!-- 分组开关 -->
            <el-form-item label="分组">
                <el-switch v-model="groupFormData.groupSwitch" />
                <el-tooltip
                    effect="dark"
                    content="分组开启后，可以添加客户端配置分组"
                    placement="top"
                >
                    <el-icon class="tip-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </el-form-item>

            <!-- 分组列表 (仅在分组开启时显示) -->
            <el-form-item label="分组名称" v-if="groupFormData.groupSwitch">
                <!-- 动态分组项 -->
                <div
                    class="group-row"
                    v-for="(group, index) in groupFormData.groups"
                    :key="index"
                >
                    <el-input
                        v-model="groupFormData.groups[index]"
                        placeholder="请输入分组名称"
                        style="width: 300px; margin-right: 10px"
                        @blur="validateGroupName(index)"
                        :class="{ 'is-error': groupErrors[index] }"
                    />
                    <el-button
                        type="primary"
                        plain
                        @click="handleViewClientUrl(group)"
                    >
                        查看客户端网址
                    </el-button>
                    <el-button
                        type="danger"
                        v-if="index >= 1"
                        @click="removeGroup(index)"
                    >
                        删除
                    </el-button>
                    <div class="error-message" v-if="groupErrors[index]">
                        {{ groupErrors[index] }}
                    </div>
                </div>

                <!-- 添加分组按钮 -->
                <div class="add-btn-row">
                    <el-button
                        circle
                        type="primary"
                        size="small"
                        @click="addGroup"
                        class="add-btn"
                    >
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-button>
                    <el-tooltip
                        effect="dark"
                        content="添加分组"
                        placement="top"
                    >
                        <el-icon class="tip-icon">
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </div>
            </el-form-item>
        </el-form>
    </div>

    <!-- 底部操作栏 -->
    <FixedActionBar :visible="true">
        <!-- 主要操作按钮 -->
        <el-button @click="$router.push('/project-list')"> 返回 </el-button>
        <el-button type="success" @click="saveSetting">
            <el-icon>
                <Setting />
            </el-icon>
            保存设置
        </el-button>
        <el-button type="primary" @click="openScreen">
            <el-icon>
                <Monitor />
            </el-icon>
            进入大屏
        </el-button>
    </FixedActionBar>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import FixedActionBar from '@/components/common/BottomActionBar.vue';

export default {
    components: {
        FixedActionBar,
    },
    props: {
        acid: {
            type: String,
            required: true,
        },
        initialData: {
            type: Object,
            default: () => ({
                groupSwitch: false,
                groups: [],
            }),
        },
    },
    data() {
        return {
            groupFormData: { ...this.initialData },
            groupErrors: {}, // 用于存储每个分组的错误信息
        };
    },
    methods: {
        validateGroupName(index) {
            const groupName = this.groupFormData.groups[index]?.trim();
            this.groupErrors[index] = ''; // 重置错误

            if (!groupName) {
                this.groupErrors[index] = '分组名称不能为空';
                return false;
            }

            // 检查是否与其他分组重复（排除自身）
            const isDuplicate = this.groupFormData.groups.some(
                (g, i) => i !== index && g?.trim() === groupName,
            );

            if (isDuplicate) {
                this.groupErrors[index] = '分组名称不能重复';
                return false;
            }

            return true;
        },
        validateAllGroups() {
            let isValid = true;

            this.groupFormData.groups.forEach((_, index) => {
                if (!this.validateGroupName(index)) {
                    isValid = false;
                }
            });

            return isValid;
        },
        async removeGroup(index) {
            const groupName = this.groupFormData.groups[index];

            if (groupName && groupName.trim() !== '') {
                try {
                    await ElMessageBox.confirm(
                        `确定要删除分组 "${groupName}" 吗？`,
                        '删除确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        },
                    );
                    this.groupFormData.groups.splice(index, 1);
                    // 删除后重新整理错误对象
                    const newErrors = {};
                    Object.keys(this.groupErrors).forEach((key) => {
                        if (key < index) newErrors[key] = this.groupErrors[key];
                        if (key > index)
                            newErrors[key - 1] = this.groupErrors[key];
                    });
                    this.groupErrors = newErrors;
                } catch {
                    console.log('用户取消了删除操作');
                }
            } else {
                this.groupFormData.groups.splice(index, 1);
                // 同上处理错误对象
                const newErrors = {};
                Object.keys(this.groupErrors).forEach((key) => {
                    if (key < index) newErrors[key] = this.groupErrors[key];
                    if (key > index) newErrors[key - 1] = this.groupErrors[key];
                });
                this.groupErrors = newErrors;
            }
        },
        addGroup() {
            this.groupFormData.groups.push('');
        },
        handleViewClientUrl(groupName) {
            console.log('查看分组:', groupName);
        },

        async saveSetting() {
            try {
                if (!this.validateAllGroups()) {
                    ElMessage.error('请修正分组设置中的错误');
                    return null;
                }

                // 这里实现保存逻辑，使用 this.acid 和 this.groupFormData
                console.log('保存分组设置', this.acid, this.groupFormData);
                return { groupSettings: this.groupFormData };
            } catch (error) {
                console.error('保存分组设置失败:', error);
                throw error;
            }
        },

        // 进入大屏
        openScreen() {
            console.log('进入大屏');
        },
    },
};
</script>

<style scoped>
.group-setting-tip-info {
    width: 95%;
    margin: 10px 20px;
    border: 1px solid #5695f3;
    background: #eaf9ff;
    border-radius: 5px;
    padding: 10px 10px;
}

.group-row {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.add-btn-row {
    display: flex;
    justify-content: center;
    margin-top: 15px;
    margin-bottom: 5px;
    width: 50%;
}

.add-btn {
    width: 32px;
    height: 32px;
}

.tip-icon {
    margin-left: 10px;
    color: #909399;
    cursor: help;
}

.el-form-item {
    margin-bottom: 22px;
}

.error-message {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    width: 100%;
    margin-left: 120px;
}

.is-error >>> .el-input__inner {
    border-color: #f56c6c;
}
</style>
